<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { useRouter, useRoute } from 'vue-router'
import { usePaperStore } from '../stores/papers'
import { Modal, Message } from '@arco-design/web-vue'
import { ref } from 'vue'

const router = useRouter()
const route = useRoute()

const isManager = ref(("manager" in route.query) ? true : false)

// 题库Store
const paperStore = usePaperStore()
const { testSync, loadPaperBaseDataList, removePaper } = paperStore
const { isLoading, isSyncing, papers } = storeToRefs(paperStore)

// 开始载入
setTimeout(loadPaperBaseDataList, 300)

// 进入测试页面
const gotoTestPaper = (paperName: string) => router.push({ name: 'testPaper', params: { paperName } })

// 同步题库
const testSyncConfirm = () => {
    Modal.confirm({
        content: '是否同步题库？',
        onOk: async () => {
            await testSync()
            await loadPaperBaseDataList()
            Message.success('同步成功')
        }
    })
}

// 删除试卷
const remove = (paperName: string) => {
    Modal.confirm({
        content: '是否删除试卷？',
        onOk: async () => {
            await removePaper(paperName)
            await loadPaperBaseDataList()
            Message.success('删除成功')
        }
    })
}


const edit = (paperName: string) => {
    router.push({
        name: 'testPaperEditor',
        params: {
            paperName
        }
    })
}

</script>

<template>

    <div v-if="isManager" class="mb-1">
        <a-button size="mini" type="primary" :disabled="isSyncing" long @click="testSyncConfirm">同步{{
            isSyncing ? "中..." : "" }}</a-button>
    </div>


    <div v-if="isLoading" class="flex flex-col w-full h-full justify-center items-center ">
        <div><a-spin :loading="true" size=30></a-spin></div>
        <div class=" text-sm">正在加载题库...</div>
    </div>

    <div v-else class="grid grid-cols-2 gap-4">
        <a-card :title="paper.name" v-for="paper in papers">

            <template #extra>
                <a-link @click="gotoTestPaper(paper.name)">进入</a-link>
            </template>

            <div class="text-sm text-gray-500">{{ paper.description }}</div>

            <div v-if="isManager" class="mt-2">
                <a-space>
                    <a-button size="mini" type="primary" @click="edit(paper.name)">编辑 </a-button>
                    <a-button size="mini" type="primary" status="warning" @click="remove(paper.name)">删除</a-button>
                </a-space>
            </div>
        </a-card>
    </div>
</template>
